package com.redxiii.spike.pmi.command;

import java.util.Map;
import java.util.Map.Entry;

import com.redxiii.spike.api.command.CommandFactory;
import com.redxiii.spike.api.command.InitializationRequired;
import com.redxiii.spike.api.message.ImMessage;
import com.redxiii.spike.api.pmi.entity.Issue;
import com.redxiii.spike.pmi.HandlerSession;
import com.redxiii.spike.pmi.commons.PmiDatabase;
import com.redxiii.spike.pmi.commons.UserSettings;
import com.redxiii.spike.util.command.InternetCommand;
import com.redxiii.spike.util.core.EngineSession;
import com.redxiii.spike.util.message.BasicMsgInterpreter;

/**
 * @author Daniel Filgueiras
 * @since 24/06/2011
 */
@InitializationRequired
@CommandFactory(BasicMsgInterpreter.class)
public class WhoIsWorking extends InternetCommand  {

	@Override
	public boolean proccess(ImMessage message) {
		
		PmiDatabase database = HandlerSession.getDatabase();
		
		StringBuilder buffer = new StringBuilder();
		
		Map<String, UserSettings> users = HandlerSession.getUserSettings();
		for (Entry<String, UserSettings> entry : users.entrySet()) {
			UserSettings settings = entry.getValue();
			if (settings.getWorkingIssue() > 0) {
				Issue issue = database.getIssue(settings.getWorkingIssue());
				buffer
					.append("\"")
					.append(entry.getKey())
					.append("\" is working on issue #")
					.append(settings.getWorkingIssue());
				if (issue != null) {
					buffer
						.append(": *\"")
						.append(issue.getSummary())
						.append("\"*");
				}
				buffer.append("\r\n");
			}
		}
		
		if (buffer.length() == 0)
			buffer.append("No one is working...");
		
		EngineSession.getCommunicationService().reply(message, buffer);
		
		return true;
	}

}
